//
//  ZYStatusPictureView.swift
//  weiboZY
//
//  Created by 赵勇 on 16/5/16.
//  Copyright © 2016年 赵勇. All rights reserved.
//

import UIKit

private let ZYStatusPictureViewCellIndentifier = "ZYStatusPictureViewCellIndentifier"

// item之前的间距
let itemMargin: CGFloat = 5
// item的宽度
let itemWidth: CGFloat = (ScreenWidth - 2 * StatusTableViewCellMargin - 2 * itemMargin) / 3

// 配图视图
class ZYStatusPictureView: UICollectionView,UICollectionViewDataSource,UICollectionViewDelegate {
    
    // 图片数据
    var picUrls: [ZYStatusPictureInfo]? {
        didSet{
            
            picNumLable.text = "\(picUrls?.count ?? 0)"
            
            let currentCGSize = calsize(picUrls?.count ?? 0)
            // 设置size约束
            self.snp_updateConstraints { (make) -> Void in
                make.size.equalTo(currentCGSize)
                
                // 重新加载
                reloadData()
            }
            
        }
    }
    
    
    // 懒加载 显示图片个数
    private var picNumLable:UILabel = UILabel(textColor: UIColor.redColor(), font: 20)
    
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        let flowLayout = UICollectionViewFlowLayout()
        // 隐藏图片个数的lable
        picNumLable.hidden = true
        
        // 设置大小
        flowLayout.itemSize = CGSize(width: itemWidth, height: itemWidth)
        // 设置间距
        flowLayout.minimumInteritemSpacing = itemMargin
        // 设置行间距
        flowLayout.minimumLineSpacing = itemMargin
        
        super.init(frame: frame, collectionViewLayout: flowLayout)
        
        setupUI()
        
   }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        backgroundColor = UIColor(white: 0.95, alpha: 1)
        addSubview(picNumLable)

        picNumLable.snp_makeConstraints { (make) -> Void in
            make.center.equalTo(self)

        }
        // 注册cell
        registerClass(ZYStatusPictureViewCell.self, forCellWithReuseIdentifier: ZYStatusPictureViewCellIndentifier)
        //设置代理源的反法
        dataSource = self
        delegate = self
        
    }
    
    // 数据源代理方法
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return picUrls?.count ?? 0
    }
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(ZYStatusPictureViewCellIndentifier, forIndexPath: indexPath) as! ZYStatusPictureViewCell
        // 设置图片数据
        cell.picInfo = picUrls![indexPath.row]
        return cell
    }
    
    // 根据图片数量计算CGSize
    private func calsize(count:Int) -> CGSize {
        // 列数计算
        let cols = count > 3 ? 3 : count
        
//        let cols = count > 4 ? 3 : count = 4 ? 2 :
        
        // 行数计算
        let rows = (count - 1) / 3 + 1
        // 当前视图的宽度
        let currentWidth = CGFloat(cols) * itemWidth +  CGFloat(cols - 1) * itemMargin
        // 当前视图的高度
        let currentheight = CGFloat(rows) * itemWidth + CGFloat(rows - 1) * itemMargin
        
        return CGSize(width: currentWidth, height: currentheight)
    }
    
    
    // 点击图片item放大图片
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
//        SDPhotoBrowser *browser = [[SDPhotoBrowser alloc] init];
//        
//        browser.sourceImagesContainerView = 原图的父控件;
//        
//        browser.imageCount = 原图的数量;
//        
//        browser.currentImageIndex = 当前需要展示图片的index;
//        
//        browser.delegate = 代理;
//        
//        [browser show]; // 展示图片浏览器
        let browser = SDPhotoBrowser()
        
        browser.sourceImagesContainerView = self
        
        browser.imageCount = picUrls?.count ?? 0
        browser.currentImageIndex = indexPath.item
        browser.delegate = self
        
        browser.show()
        
    }
    
    
}



extension ZYStatusPictureView: SDPhotoBrowserDelegate {
    
//    // 返回临时占位图片（即原来的小图）
//    
//    (UIImage *)photoBrowser:(SDPhotoBrowser *)browser placeholderImageForIndex:(NSInteger)index { ； }
//    // 返回高质量图片的url
//    
//    (NSURL *)photoBrowser:(SDPhotoBrowser *)browser highQualityImageURLForIndex:(NSInteger)index { ； }
    func photoBrowser(browser: SDPhotoBrowser!, placeholderImageForIndex index: Int) -> UIImage! {
        let indexPath = NSIndexPath(forItem: index, inSection: 0)
        let cell = self.cellForItemAtIndexPath(indexPath)! as! ZYStatusPictureViewCell
        
        return cell.imageView.image
    }
    
    func photoBrowser(browser: SDPhotoBrowser!, highQualityImageURLForIndex index: Int) -> NSURL! {
        
        let urlStr = picUrls![index].thumbnail_pic!.stringByReplacingOccurrencesOfString("thumbnail", withString: "bmiddle")
        
        return NSURL(string: urlStr)
    }
    
}


// 自定义配图模型cell
class ZYStatusPictureViewCell: UICollectionViewCell {
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
        
    }
    // 设置模型
    var picInfo:ZYStatusPictureInfo? {
        didSet{
            guard let url = picInfo?.thumbnail_pic else{
                return
            }
            
            imageView.sd_setImageWithURL(NSURL(string: url), placeholderImage: UIImage(named:"timeline_image_placeholder" ))
            
            gifImageView.hidden = !url.hasSuffix(".gif")
            
        }
    }
 
    // 图片
    
    private lazy var imageView: UIImageView = {
       let view = UIImageView(image: UIImage(named: "timeline_image_placeholder"))
        // 设置图片等比填充
        view.contentMode = UIViewContentMode.ScaleAspectFill
        // 裁剪多余部分
        view.clipsToBounds = true
        
        return view
    }()
    // gif图片
    private lazy var gifImageView:UIImageView = UIImageView(image: UIImage(named:"timeline_image_gif"))
    
    
    private func setupUI() {
        
//        backgroundColor = RandomColor()
        contentView.addSubview(imageView)
        contentView.addSubview(gifImageView)
        // 设置约束
        imageView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(contentView).offset(UIEdgeInsetsZero)
        }
        
        gifImageView.snp_makeConstraints { (make) -> Void in
            make.trailing.equalTo(contentView)
            make.bottom.equalTo(contentView)
        }
    }
    
}









